﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LED_Editor.Model;
using System.IO.Ports;
using LED_Editor.Config;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Collections;
using BLToolkit.EditableObjects;
using BLToolkit.Reflection;


namespace LED_Editor.Model {
	[Serializable]
	public abstract class Track : EditableObject<Track>, IEnumerable {

		public Track() {
			_frameCollection = new FrameSource();
			_frameCollection.SetTrack(this);
			_frameCollection.ListChanged += new System.ComponentModel.ListChangedEventHandler(_frameCollection_ListChanged);
			// _controller = new Controller(new SerialPort(SerialPortSettings.Instance.Port,SerialPortSettings.Instance.   ) )  
		}


		public abstract int UniqueId { get; set; }

		public abstract int Id { get; set; }
		//{ 
		//    get { return _id; } 
		//    set { _id = value;

		//    }
		//}
		public abstract string Name { get; set; }

		public abstract bool Selected { get; set; }

		public abstract bool IsReady { get; set; }

		public abstract Color Color { get; set; }

		public abstract Color IsAvailableColor { get; set; }


		//public static Track CreateInstance()
		//{
		//    Track track = TypeAccessor.CreateInstance<Track>();
		//    return track;
		//}

		private FrameSource _frameCollection;

		public FrameSource Frames {
			get { return _frameCollection; }
		}

		//private SerialPortSettings _serialPortSettings;

		//public SerialPortSettings SerialPortSettings
		//{
		//    get {
		//        if (_serialPortSettings == null)
		//            _serialPortSettings = new SerialPortSettings();  
		//        return _serialPortSettings; }
		//}

		public int TotalFramesDuration {
			get {
				int total = 0;
				foreach (Frame item in Frames) {
					total += item.FrameDuration;
				}
				return total;
			}
		}

		public int TotalFramesDurationMilliseconds {
			get {
				return TotalFramesDuration * 10;
			}
		}

		public Frame GetNewFrame() {
			Frame previous = null;
			if (this.Frames.Count > 0) {
				previous = (Frame)Frames[Frames.Count - 1];
			}

			Frame newFrame = Frame.CreateInstance();
			newFrame.TrackId = Id;
			newFrame.FrameDuration = 100;
			if (previous == null) {
				newFrame.StartColor = Color.Black;
				newFrame.EndColor = Color.Black;
			} else {
				newFrame.StartColor = previous.EndColor;
			}
			return newFrame;
		}

		#region IEnumerable Members

		public IEnumerator GetEnumerator() {
			return ((IEnumerable)_frameCollection).GetEnumerator();
		}

		#endregion

		void _frameCollection_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) {
			_changed = true;
		}

		private bool _changed = true;
		public bool Changed {
			get {
				//Frames.
				return _changed;
			}
			set { _changed = value; }
		}
	}
}
